package com.hxd.mall.module.jpush

import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.os.Bundle
import android.text.TextUtils
import android.util.Log
import com.hxd.mall.constant.HxdConstantsAccount
import com.hxd.mall.constant.HxdConstantsRouterPath.Product.path_hxd_main_page
import com.hxd.mall.module.EventBean
import com.hxd.mall.module.MainActivity
import com.hxd.mall.module.account.login.LoginActivity
import com.hxd.mall.utils.local.ActivityUtil
import com.hxd.mall.utils.local.ActivityUtil.sendEventBus
import com.hxd.mall.utils.local.NavigationUtil.routerNavigation
import com.hxd.mall.utils.local.StackManageUtil
import com.hxd.mall.utils.local.StackManageUtil.closeOtherOnlyActivity
import com.hxd.mall.utils.local.StackManageUtil.currentActivity
import com.hxd.mall.utils.open.GsonUtil
import com.hxd.threelibrary.getJPushClient
import com.orhanobut.logger.Logger
import org.json.JSONException
import org.json.JSONObject

/**
 * push广播接受类
 * 1. 无参数，默认打开app
 * 2. 有参数，根据参数类型调整到对应类
 *  {"action":"nativeBankCardViewController@\/sign\/sign","parms":"{\"messageType\":1}","target":"Profile@\/hxd\/main\/page","transformType":"1"}
 */
class PushBroadcastReceiver : BroadcastReceiver() {
    private val tag = "PushBroadcastReceiver"

    override fun onReceive(context: Context?, intent: Intent?) {
        try {
            val bundle = intent?.extras
            Log.d(tag, "[MyReceiver] onReceive - " + intent?.action + ", extras: " + printBundle(bundle!!))

            //{"path":"personalCenter"}
            val json = bundle.getString(getJPushClient().EXTRA_EXTRA) ?: ""
            Log.d(tag, "[MyReceiver] onReceive -  json  ：$json")

            if (HxdConstantsAccount.isLogin && json.isNotEmpty()) {

                val bean = GsonUtil.json2bean(json, JPushBean::class.java)
                when (bean.path) {
                    "personalCenter", "fansManage" -> {
                        closeOtherOnlyActivity(MainActivity(), path_hxd_main_page)
                        if (currentActivity() != null && currentActivity()!!::class.java != MainActivity::class.java) {
                            routerNavigation(path_hxd_main_page)
                        }
                        sendEventBus(EventBean(2))
                    }
                }
            }

            if (getJPushClient().ACTION_NOTIFICATION_OPENED == intent.action) {
                Log.d(tag, "[MyReceiver] 用户点击打开了通知")
                routerNavigation(path_hxd_main_page)
            }

//            when {
//                getJPushClient().ACTION_REGISTRATION_ID == intent.action -> {
//                    val regId = bundle.getString(getJPushClient().EXTRA_REGISTRATION_ID)
//                    Log.d(tag, "[MyReceiver] 接收Registration Id : " + regId!!)
//                    //send the Registration Id to your server...
//                }
//                getJPushClient().ACTION_MESSAGE_RECEIVED == intent.action -> {
//                    Log.d(tag, "[MyReceiver] 接收到推送下来的自定义消息: " + bundle.getString(getJPushClient().EXTRA_MESSAGE)!!)
//                    processCustomMessage(context!!, bundle)
//                }
//                getJPushClient().ACTION_NOTIFICATION_RECEIVED == intent.action -> {
//                    Log.d(tag, "[MyReceiver] 接收到推送下来的通知")
//                    val notifactionId = bundle.getInt(getJPushClient().EXTRA_NOTIFICATION_ID)
//                    Log.d(tag, "[MyReceiver] 接收到推送下来的通知的ID: $notifactionId")
//                }
//                getJPushClient().ACTION_NOTIFICATION_OPENED == intent.action -> {
//                    Log.d(tag, "[MyReceiver] 用户点击打开了通知")
//
//                    routerNavigation(path_hxd_main_page)
//                }
//                getJPushClient().ACTION_RICHPUSH_CALLBACK == intent.action -> Log.d(tag, "[MyReceiver] 用户收到到RICH PUSH CALLBACK: " + bundle.getString(getJPushClient().EXTRA_EXTRA)!!)
//                //在这里根据 JPushInterface.EXTRA_EXTRA 的内容处理代码，比如打开新的Activity， 打开一个网页等..
//                getJPushClient().ACTION_CONNECTION_CHANGE == intent.action -> {
//                    val connected = intent.getBooleanExtra(getJPushClient().EXTRA_CONNECTION_CHANGE, false)
//                    Log.d(tag, "[MyReceiver]" + intent.action + " connected state change to " + connected)
//                }
//                else -> Log.d(tag, "[MyReceiver] Unhandled intent - " + intent.action!!)
//            }
        } catch (e: Exception) {
            e.printStackTrace()
        }
    }

    // 打印所有的 intent extra 数据
    private fun printBundle(bundle: Bundle): String {
        val sb = StringBuilder()
        for (key in bundle.keySet()) {
            if (key == getJPushClient().EXTRA_NOTIFICATION_ID) {
                sb.append("\nkey:" + key + ", value:" + bundle.getInt(key))
            } else if (key == getJPushClient().EXTRA_CONNECTION_CHANGE) {
                sb.append("\nkey:" + key + ", value:" + bundle.getBoolean(key))
            } else if (key == getJPushClient().EXTRA_EXTRA) {
                if (TextUtils.isEmpty(bundle.getString(getJPushClient().EXTRA_EXTRA))) {
                    Logger.i(tag, "This message has no Extra data")
                    continue
                }
                try {
                    val json = JSONObject(bundle.getString(getJPushClient().EXTRA_EXTRA)!!)

                    val it = json.keys()

                    while (it.hasNext()) {
                        val myKey = it.next()
                        sb.append(
                            "\nkey:" + key + ", value: [" +
                                    myKey + " - " + json.optString(myKey) + "]"
                        )
                    }
                } catch (e: JSONException) {
                    Logger.e(tag, "Get message extra JSON error!")
                }

            } else {
                sb.append("\nkey:" + key + ", value:" + bundle.get(key))
            }
        }
        return sb.toString()
    }

    //send msg to MainActivity
    private fun processCustomMessage(context: Context, bundle: Bundle) {
        /*if (MainActivity.isForeground) {
            val message = bundle.getString(getJPushClient().EXTRA_MESSAGE)
            val extras = bundle.getString(getJPushClient().EXTRA_EXTRA)
            val msgIntent = Intent(MainActivity.MESSAGE_RECEIVED_ACTION)
            msgIntent.putExtra(MainActivity.KEY_MESSAGE, message)
            if (!ExampleUtil.isEmpty(extras)) {
                try {
                    val extraJson = JSONObject(extras!!)
                    if (extraJson.length() > 0) {
                        msgIntent.putExtra(MainActivity.KEY_EXTRAS, extras)
                    }
                } catch (e: JSONException) {

                }

            }
            LocalBroadcastManager.getInstance(context).sendBroadcast(msgIntent)
        }*/
    }

}